package aor2.components;

public class Clock implements Comparable<Clock>, Cloneable {

	private int currentClkPart;// current phase
	private int clkParts;// number of phases in one clock

	public Clock(int t, int currentClkPart, int clkParts) {
		super();
		this.clkParts = clkParts;
		this.currentClkPart = t * clkParts + currentClkPart;
	}

	public Clock(int clkParts) {
		this(0, 0, clkParts);
	}

	public Clock(int t, int currentClkPart) {
		this(t, currentClkPart, 2);
	}

	public Clock() {
		this(0, 0);
	}

	public int getT() {
		return currentClkPart / clkParts;
	}

	public int getPhase() {
		return currentClkPart % clkParts;
	}

	public void setT(int t) {
		currentClkPart = Math.max(t, 0) * clkParts;
	}

	public int getCurrentClkPart() {
		return currentClkPart;
	}

	public void setCurrentClkPart(int currentClkPart) {
		this.currentClkPart = currentClkPart;
	}

	public void nextClkPart() {
		currentClkPart++;
	}

	public void previousClkPart() {
		if (currentClkPart == 0)
			return;
		else if (currentClkPart % clkParts == 0)
			currentClkPart -= clkParts;
		else
			currentClkPart -= ((currentClkPart % clkParts) + clkParts);
	}

	public void nextT() {
		do
			currentClkPart++;
		while (currentClkPart % clkParts != 0);
	}

	public boolean isNewClkStarted() {
		return currentClkPart == 0;
	}

	@Override
	public int compareTo(Clock o) {
		return currentClkPart - o.currentClkPart;
	}

	@Override
	public Clock clone() {
		Clock clk = null;
		try {
			clk = (Clock) super.clone();
		} catch (Exception e) {
			System.out.println("clock clone error.");
		}
		return clk;
	}

}
